package com.huashi.dealer.modular.business.upload.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.commonEntity.UploadGroup;
import com.huashi.dealer.modular.business.upload.mapper.UploadFileMapper;
import com.huashi.dealer.modular.business.upload.mapper.UploadGroupMapper;
import com.huashi.dealer.modular.business.upload.service.UploadGroupService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文件库分组Service实现类
 */
@Service
public class UploadGroupServiceImpl extends ServiceImpl<UploadGroupMapper, UploadGroup> implements UploadGroupService {

    @Resource
    private UploadGroupMapper uploadGroupMapper;

    @Resource
    private UploadFileMapper uploadFileMapper;

    @Override
    public List<UploadGroup> getGroupList(String groupType) {
        return uploadGroupMapper.selectByGroupType(groupType);
    }

    @Override
    public UploadGroup addGroup(String groupName, String groupType) {
        UploadGroup uploadGroup = new UploadGroup();
        uploadGroup.setGroupName(groupName);
        uploadGroup.setGroupType(groupType);
        uploadGroup.setSort(100);
        uploadGroup.setCreateTime(System.currentTimeMillis() / 1000);
        
        uploadGroupMapper.insert(uploadGroup);
        return uploadGroup;
    }

    @Override
    public boolean editGroup(Long groupId, String groupName) {
        UploadGroup uploadGroup = uploadGroupMapper.selectById(groupId);
        if (uploadGroup == null) {
            return false;
        }
        
        uploadGroup.setGroupName(groupName);
        uploadGroup.setUpdateTime(System.currentTimeMillis() / 1000);
        
        return uploadGroupMapper.updateById(uploadGroup) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteGroup(Long groupId) {
        // 先将该分组下的所有文件移到未分组(group_id = 0)
        LambdaQueryWrapper<UploadFile> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(UploadFile::getGroupId, groupId);
        
        UploadFile updateFile = new UploadFile();
        updateFile.setGroupId(0L);
        uploadFileMapper.update(updateFile, updateWrapper);
        
        // 删除分组（软删除）
        UploadGroup uploadGroup = uploadGroupMapper.selectById(groupId);
        if (uploadGroup == null) {
            return false;
        }
        
        return uploadGroupMapper.deleteById(groupId) > 0;
    }
}
